package com.seanliao.nav.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seanliao.nav.common.domain.dto.LoginByUsernameDTO;
import com.seanliao.nav.common.domain.vo.LoginVO;
import com.seanliao.nav.common.domain.vo.RoleVO;
import com.seanliao.nav.common.exception.BusinessException;
import com.seanliao.nav.common.response.Result;
import com.seanliao.nav.common.response.ResultBuilder;
import com.seanliao.nav.entity.SysPermission;
import com.seanliao.nav.entity.SysRole;
import com.seanliao.nav.entity.SysUser;
import com.seanliao.nav.security.MyUserDetails;
import com.seanliao.nav.security.UserPrincipleMapHolder;
import com.seanliao.nav.service.ISysPermissionService;
import com.seanliao.nav.service.ISysRoleService;
import com.seanliao.nav.service.ISysUserService;
import com.seanliao.nav.util.PasswordUtil;
import com.seanliao.nav.util.SecurityUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/login")
@RequiredArgsConstructor
public class LoginController {

    private final ISysUserService userService;
    private final ISysRoleService roleService;
    private final ISysPermissionService permissionService;
    private final UserPrincipleMapHolder userPrincipleMapHolder;

    /**
     * 登录
     */
    @RequestMapping("/username")
    public Result<LoginVO> loginByUsername(HttpSession httpSession, @RequestBody LoginByUsernameDTO loginDTO) {
        SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, loginDTO.getUsername()));
        Assert.notNull(sysUser, () -> new BusinessException("用户不存在"));
        boolean passwordMatch = PasswordUtil.match(loginDTO.getPassword(), sysUser.getPassword());
        Assert.isTrue(passwordMatch, () -> new BusinessException("密码错误"));
        Assert.isFalse(sysUser.getIsBan(), () -> new BusinessException("该账号已被封禁"));
        // 角色
        List<RoleVO> roles = roleService.listByUserId(sysUser.getId());
        Map<String, String> availableRoles = new HashMap<>(roles.size());
        roles.forEach(role -> availableRoles.put(role.getCode(), role.getName()));
        // 权限
        List<Long> roleIds = roles.stream().map(RoleVO::getId).toList();
        List<SysPermission> permissions = permissionService.listPermissionByRoleIds(roleIds);
        List<String> permissionCodes = permissions.stream().map(SysPermission::getCode).toList();
        // 用户信息构造
        Object OldPrinciple = userPrincipleMapHolder.get(sysUser.getId());
        MyUserDetails myUserDetails;
        if (OldPrinciple instanceof MyUserDetails) {
            myUserDetails = (MyUserDetails) OldPrinciple;
        } else {
            myUserDetails = new MyUserDetails(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), sysUser.getIsBan());
        }
        myUserDetails.setNickname(sysUser.getNickname());
        myUserDetails.setPermissions(permissionCodes);
        myUserDetails.setRoles(availableRoles);
        myUserDetails.setAvailableRoles(availableRoles);
        // 保存用户信息
        SecurityUtil.setCurrentUser(httpSession, myUserDetails);
        // 保存用户Principle映射
        userPrincipleMapHolder.set(sysUser.getId(), myUserDetails);
        // 返回
        LoginVO loginVO = new LoginVO();
        loginVO.setUsername(sysUser.getUsername());
        loginVO.setUserId(sysUser.getId());
        loginVO.setNickname(sysUser.getNickname());
        loginVO.setPermissions(permissionCodes);
        loginVO.setRoles(availableRoles);
        loginVO.setAvailableRoles(availableRoles);
        return ResultBuilder.success(loginVO);
    }

    /**
     * 选择角色
     * 用户登录后若有多个角色，用户可自行选择以其中某个角色登录
     */
    @RequestMapping("/select-role")
    public Result<LoginVO> selectRole(HttpSession httpSession,
                                      @RequestParam String roleCode
    ) {
        // 这时需要先登录才可使用
        MyUserDetails myUserDetails = SecurityUtil.getCurrentUser();
        Assert.notNull(myUserDetails, () -> new BusinessException("尚未登录"));
        // 当前拥有的角色
        Map<String, String> availableRoles = myUserDetails.getAvailableRoles();
        Assert.isTrue(availableRoles.containsKey(roleCode), () -> new BusinessException("无效角色"));
        Assert.isTrue(availableRoles.keySet().size() > 1, () -> new BusinessException("单一角色无需切换"));
        // 选择的角色，重新从数据库获取角色
        SysRole sysRole = roleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, roleCode));
        // 重新从数据库获取权限
        List<SysPermission> permissions = permissionService.listPermissionByRoleIds(Collections.singletonList(sysRole.getId()));
        // 重新保存用户信息
        Map<String, String> roles = Collections.singletonMap(sysRole.getCode(), sysRole.getName());
        myUserDetails.setRoles(roles);
        List<String> permissionCodes = permissions.stream().map(SysPermission::getCode).toList();
        myUserDetails.setPermissions(permissionCodes);
        // 不确定session在内存还是redis，故手动设置一遍
        SecurityUtil.setCurrentUser(httpSession, myUserDetails);
        // 重新返回用户信息
        LoginVO loginVO = new LoginVO();
        loginVO.setUsername(myUserDetails.getUsername());
        loginVO.setUserId(myUserDetails.getUserId());
        loginVO.setNickname(myUserDetails.getNickname());
        loginVO.setPermissions(permissionCodes);
        loginVO.setRoles(roles);
        loginVO.setAvailableRoles(availableRoles);
        return ResultBuilder.success(loginVO);
    }

    /**
     * 登出
     */
    @RequestMapping("/logout")
    public Result<?> logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        // 这时需要先登录才可使用
        MyUserDetails myUserDetails = SecurityUtil.getCurrentUser();
        Assert.notNull(myUserDetails, () -> new BusinessException("尚未登录"));
        // 移除会话中的登录信息
        SecurityUtil.clearCurrentUser(session);
        // security接口登出
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        new SecurityContextLogoutHandler().logout(request, response, authentication);
        return ResultBuilder.success();
    }


}
